/**
 * 
 */
package com.livemeter;

import java.util.ArrayList;

import com.livemeter.PollOption;
import com.livemeter.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;


/**
 *
 *Activity to show/activate available polls and topics.
 */
public class PollResultsActivity extends Activity 
{
	private Poll currentPoll;
	private ArrayList<ExtendedProgressBar> progressBarsOptions = new ArrayList<ExtendedProgressBar>();
	private TextView labelCountOfVotes;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {   
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.poll_results);
     
  
        Button closePollButton = (Button) findViewById(R.id.pres_ClosePollButton);
        
        // only master can close poll
        if(!LIM_Engine.getInstance().isMaster()) {
        	closePollButton.setVisibility(View.GONE);
        } else {
            closePollButton.setOnClickListener( new OnClickListener() {
            	public void onClick(View v)
            	{
            		PollResultsActivity.this.onClosePollClicked();
            	}
            } );
        }
        
        View closeButton = findViewById(R.id.pres_okButton);
        
        closeButton.setOnClickListener( new OnClickListener() {
        	public void onClick(View v)
        	{
        		PollResultsActivity.this.finish();
        	}
        } );
        
        Bundle extras = getIntent().getExtras();      
        currentPoll = Poll.getPoll(extras.getString("PollTitle"));
        
        initPollResults();
        updatePollResults();
        
    	LIM_Engine lim = LIM_Engine.getInstance();
		lim.removeEventListener(m_clientLIMEventListener);
		lim.addEventListener(m_clientLIMEventListener);
    }
    

    LIM_Event_Listener m_clientLIMEventListener = new LIM_Event_Listener() {
		@Override
		public void meterValueChanged(LIM_MeterValueEvent evt) {}
		@Override
		public void pollOpened(LIM_PollEvent evt) {}
		@Override
		public void pollUpdated(LIM_PollEvent evt) 
		{
			Log.i("LIM-PRA", "Poll Updated: "+evt.poll.getTitle());
			if (evt.poll.getTitle().equalsIgnoreCase(currentPoll.getTitle()))
			{
				PollResultsActivity.this.runOnUiThread(new Runnable() {
			        	public void run() {updatePollResults();}
			        }
			   ); 
			}
		}
		@Override
		public void pollClosed(LIM_PollEvent evt) {}
		@Override
		public void meterOpened(LIM_MeterEvent evt) {}
		@Override
		public void meterClosed(LIM_MeterEvent evt) {}
		@Override
		public void questionsChanged() {}
		@Override
		public void topicStamp(LIM_TopicStampEvent evt) {}
		@Override
		public void setupTimeout() {}
		@Override
		public void tick() {}
    };

    PowerManager.WakeLock wl = null;

    @Override
    protected void onResume() {
    	super.onResume();
    	//prevent standby
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "LIM_IMA");
        wl.acquire();
    }
    @Override
    protected void onPause() {
    	//release standby
    	wl.release();
    	super.onPause();
    }
    
    
    /**
     * Converts dip to pixel
     *
     */
    public float convertDipToPixel(int dip) 
    {
    	return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, this.getResources().getDisplayMetrics());
    } 
    
    /* Update GUI to show new poll-vote values.
     * 
     * Parameters: 
     * newCountOfVotes - count of votes for this poll option provided by indexVoteOption.
     * newMaxCountOfAllVotes - count of all votes for ALL options for current poll (needed to update percentage shown on progressBars)
     */
    private void updateVotes(int indexVoteOption, int newCountOfVotes, int newMaxCountOfAllVotes)
    {
    	ExtendedProgressBar progressForOption = this.progressBarsOptions.get(indexVoteOption);
    	progressForOption.setMax(newMaxCountOfAllVotes);
    	progressForOption.setProgress(newCountOfVotes);
    }

    private void updatePollResults()
    {
    	if(this.currentPoll == null)
    		return;
    	
    	ArrayList<PollOption> pos = this.currentPoll.getOptions(false);
    	int sumVotes = 0;
    	for(PollOption option : pos)
    	{
    		sumVotes += option.getVotesForOption();
    	}

    	Log.i("LIM-PRA", "Updating Poll Results! sumVotes: "+sumVotes);
    	
    	String s = this.getString(R.string.CountOfVotes) + sumVotes;
    	if (!this.currentPoll.isActive())
    		s += "\n\n" + this.getString(R.string.PollClosed);
    	labelCountOfVotes.setText(s);
    	
    	int i = 0;
    	for(PollOption option : pos)
    	{
        	Log.d("LIM-PRA", "Option " + i + " Votes: " + option.getVotesForOption()+ " / " + sumVotes);
    		updateVotes(i,option.getVotesForOption(),sumVotes);
    		++i;
    	}
    	Log.d("LIM-PRA", "Update Poll Finished: "+i);
    }
    
    /*
     * Method sets up controls to display votes for poll
     * */
    private void initPollResults()
    {
    	if(this.currentPoll == null)
    		return;
    	
    	progressBarsOptions.clear();
    	
    	LinearLayout layout = (LinearLayout) this.findViewById(R.id.pollResultsLayout);
    	
    	LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	
    	TextView pollTitle = new TextView(this);
    	pollTitle.setLayoutParams(lp);
    	pollTitle.setText(currentPoll.getQuestion());
    	pollTitle.setTextSize(25);
    	layout.addView(pollTitle, 0);
    	
    	lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	lp.setMargins(0, (int) convertDipToPixel(30), 0, 0);
    	
    	LinearLayout.LayoutParams horizontalLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	horizontalLayoutParams.setMargins(0, (int) convertDipToPixel(15), 0, 0);
    
    	
    	lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	lp.setMargins(0, 0, 0, 0);
    	lp.weight = 1;
    	
    	LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(90, LinearLayout.LayoutParams.WRAP_CONTENT);
    	lpp.gravity = Gravity.CENTER_VERTICAL;
    	lpp.setMargins((int) convertDipToPixel(5), 0, 0, 0);
 
    	
    	int i = 1;
    	
    	for(PollOption option : this.currentPoll.getOptions(false))
    	{
    		LinearLayout ll = new LinearLayout(this);
    		ll.setOrientation(LinearLayout.HORIZONTAL);
    		ll.setLayoutParams(horizontalLayoutParams);
    		
    		TextView labelOption = new TextView(this);
    		labelOption.setLayoutParams(lp);
    		labelOption.setText(option.getOption());
    		labelOption.setTextSize(15);
    		ll.addView(labelOption);
        	
     	
        	ExtendedProgressBar optionProgressBar = new ExtendedProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
        	optionProgressBar.setClickable(false);
        	optionProgressBar.setLayoutParams(lpp);
        	ll.addView(optionProgressBar);
        	progressBarsOptions.add(optionProgressBar);
        	
        	layout.addView(ll, i++);
    	}
    	
    	lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    	lp.setMargins(0, (int) convertDipToPixel(50), 0, 0);
    	
    	TextView labelPoll = new TextView(this);
    	labelPoll.setTextSize(20);
    	labelPoll.setLayoutParams(lp);
    	labelCountOfVotes = labelPoll;
    	layout.addView(labelPoll, i);
    }

    /*
     * Master clicked button to close poll currently displayed by this activity.
     * */
	private void onClosePollClicked() 
	{
		LIM_Engine.getInstance().master_ClosePoll(currentPoll.getTitle());
		this.finish();
	}

}
